#!/usr/bin/python
#-*- coding: utf-8 -*-

# subversion info:
# $HeadURL: $
# $Author: $
# $Id: $
# $Revision: $

"""
  subdownloader: Download subtitles for a video file in a selected language.
  Authors = Rafael Treviño <skasi.7@gmail.es>
  Date = 23/10/09
"""

# Imports externals
import os
import sys
import tempfile
import subprocess

# Imports internals


def download(video, language):
  """
  Sphinx doc.
  """
  # Check video file existance # 
  if not os.access(video, os.R_OK):
    return 3

  # Create a $tempDir #
  tempDir = tempfile.mkdtemp(prefix='subdownloader', dir='/tmp')

  # Copy video file to $tempDir #
  tempFile = os.path.join(tempDir, os.path.basename(video))
  os.symlink(video, tempFile)
  
  # Run subdownloader -c -l $language -v $video #
  params = ['subdownloader', '-c', '-l', language, '-V', tempFile]
  print >> sys.stderr, 'Running "%s"' % ' '.join(params)
  retCode = subprocess.call(params)
  print >> sys.stderr, 'subdownloader returned %d on exit' % retCode
  if retCode:
    return 3
  
  # If success (return code?) rename and move back subtitles file #
  subtitle = '.'.join(video.split('.')[:-1] + ['srt'])
  print >> sys.stderr, 'Subtitle file will be "%s"' % subtitle
  for file in os.listdir(tempDir):
    if file.endswith('.srt'):
      params = ['mv', os.path.join(tempDir, file), subtitle]
      print >> sys.stderr, 'Running "%s"' % ' '.join(params)
      retCode = subprocess.call(params)
      print >> sys.stderr, 'mv returned %d on exit' % retCode
      if not retCode:
        # Everything ok
        break
  else:
    print >> sys.stderr, 'No subtitle file was found'
    return 3
  
  # Remove $tempDir #
  params = ['rm', '-rf', tempDir]
  print >> sys.stderr, 'Running "%s"' % ' '.join(params)
  retCode = subprocess.call(params)
  print >> sys.stderr, 'rm returned %d on exit' % retCode

  return 0


# Main entry point
if __name__ == '__main__':
  # TODO: Better logging and options
  try:
    video = os.path.abspath(sys.argv[1])
  except IndexError:
    print >> sys.stderr, 'Usage: %s <video file> [language]' % sys.argv[0]
    sys.exit(1)
  if video:
    print >> sys.stderr, 'Using video filename "%s"' % video
  else:
    print >> sys.stderr, 'Unable to determine the video filename'
    sys.exit(1)

  try:
    language = sys.argv[2]
    langSource = 'arguments'
  except IndexError:
    language = os.environ['LANG'].split('.')[0]
    langSource = 'environment'
  if language:
    print >> sys.stderr, 'Using language "%s" from %s' % (language,
        langSource)
  else:
    print >> sys.stderr, 'Unable to determine the download language'
    sys.exit(2)

  sys.exit(download(video, language))

